﻿using CallCenter.Data;
using CallCenter.Data.Models;
using CallCenter.Security;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CallCenter.Data.BizUtilities;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;

namespace CallCenter.Web.Controllers
{
    public class AccountController : Controller
    {
        public IFormsAuthentication FormsAuth = null;
        private MembershipProvider provider = null;
        /// <summary>
        /// Initializes a new instance of the <see cref="AccountController"/> class.
        /// </summary>
        public AccountController()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["mainConnection"].ConnectionString;

            this.Bridge = new DataManager(connectionString);

            this.FormsAuth = new FormsAuthenticationService(this.Bridge);
            this.provider = new CallCenterMembershipProvider(this.Bridge);
        }
        /// <summary>
        /// Logins the specified return URL.
        /// </summary>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns></returns>
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToLocal(returnUrl);
            }
            ViewBag.Error = "";
            return View("Login");
        }

        /// <summary>
        /// Logins the specified loginviewmodel.
        /// </summary>
        /// <param name="loginviewmodel">The loginviewmodel.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel loginviewmodel, string returnUrl)

        {
            if (ModelState.IsValid)
            {
                if (provider.ValidateUser(loginviewmodel.UserName.ToLower(), loginviewmodel.Password))
                {
                    var user = this.Bridge.AccountUtility.GetUser(loginviewmodel.UserName.ToLower());

                    FormsAuth.SignIn(loginviewmodel.UserName.ToLower(), user.Id, true,user.RoleName);
                    return RedirectToLocal(returnUrl);
                }
                ViewBag.Error = "The user name or password provided is incorrect.";
                ModelState.AddModelError("ErrorText", "The user name or password provided is incorrect.");
            }

            return View("Login", loginviewmodel);
        }

        /// <summary>
        /// Logs the out.
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOut()
        {
            this.FormsAuth.SignOut();

            // Delete all cookies
            string[] myCookies = Request.Cookies.AllKeys;
            foreach (string cookie in myCookies)
            {
                Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
            }
            return RedirectToAction("Login");
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            RegisterViewModel viewModel = new RegisterViewModel();
            List<RoleModelVM> roleModelVmList = this.Bridge.Role.GetRoles();
            ViewBag.RoleId = new System.Web.Mvc.SelectList(roleModelVmList, "Id", "RoleName");

            List<ContactGridViewModel> employeeList = this.Bridge.ccContactUtility.GetAllContacts();
            ViewBag.ContactName = new System.Web.Mvc.SelectList(employeeList, "id", "contactname");
            return View("Register", viewModel);
        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterViewModel user)
        {
            List<RoleModelVM> roleModelVmList = this.Bridge.Role.GetRoles();
            ViewBag.RoleId = new System.Web.Mvc.SelectList(roleModelVmList, "Id", "RoleName", user.RoleId);


            List<ContactGridViewModel> employeeList = this.Bridge.ccContactUtility.GetAllContacts();
            ViewBag.ContactName = new System.Web.Mvc.SelectList(employeeList, "id", "contactname",user.ContactId);
            //Show all contacts drodown
            //List<ContactGridViewModel> employeeList = this.Bridge.ccContactUtility.GetAllContacts();
            //ViewBag.employeeId = new System.Web.Mvc.SelectList(employeeList, "id", "contactname",)

            string result = this.Bridge.Accounts.RegisterUser(user);
            if (result != "")
            {

                ViewBag.Message = result;
                return View();
                //return this.RedirectToAction("Login");
            }
            else
            {
                ViewBag.Message = "Email or Username is already present";
                return View(user);
            }

        }

        [AllowAnonymous]
        public ActionResult PasswordReset()
        {
            RegisterViewModel viewModel = new RegisterViewModel();
            List<UserModelVm> UserModelVmList = this.Bridge.Role.GetRegisterUsers();
            ViewBag.UserName = new System.Web.Mvc.SelectList(UserModelVmList, "UserName", "UserName");
            return View(viewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AccessMenuSetUp(RegisterViewModel user)
        {

            List<RoleModelVM> roleModelVmList = this.Bridge.Role.GetRoles();
            ViewBag.RoleId = new System.Web.Mvc.SelectList(roleModelVmList, "Id", "RoleName", user.RoleId);

            IList<FeaturesVM> result = this.Bridge.MenuUtility.GetMenuAccessSetUp();


            ViewBag.Message = result;
            return View();



        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PasswordReset(RegisterViewModel user)
        {
            this.Bridge.Role.UpdateRegisterUsers(user);
            List<UserModelVm> UserModelVmList = this.Bridge.Role.GetRegisterUsers();
            ViewBag.UserName = new System.Web.Mvc.SelectList(UserModelVmList, "UserName", "UserName");
            ViewBag.Message = "user is updated";
            return View(user);
        }

        /// <summary>
        /// Redirects to local.
        /// </summary>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns>Redirects to the url when returnurl is valid or otherwise redirects to home</returns>
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                if (this.Session["UserRole"] != null)
                {
                    var role = this.Session["UserRole"].ToString();
                    return RedirectToAction("ScratchHistory", "ScratchPad");

                    //switch (role)
                    //{
                    //    case "admin":
                    //        return RedirectToAction("ScratchHistory", "ScratchPad");
                    //    case "user":
                    //        return RedirectToAction("ScratchHistory", "ScratchPad");
                    //}
                    //return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public DataManager Bridge { get; set; }

        public ActionResult ManageUser()
        {
            List<RegisterViewModel> RegisterViewModelList = this.Bridge.Accounts.GetListOfUsers();
            ViewBag.UserID = new System.Web.Mvc.SelectList(RegisterViewModelList, "Id", "UserName");
            List<RoleModelVM> roleModelVmList = this.Bridge.Role.GetRoles();
            ViewBag.RoleId = new System.Web.Mvc.SelectList(roleModelVmList, "Id", "RoleName");
            return View();
        }

        [HttpPost]
        public ActionResult ManageUser(RoleUserModel RegisterModel)
        {
            ViewBag.Message = "User Role were updated Successfully";
            this.Bridge.RoleUser.UpdateRoleUser(RegisterModel);
            List<RegisterViewModel> RegisterViewModelList = this.Bridge.Accounts.GetListOfUsers();
            ViewBag.UserID = new System.Web.Mvc.SelectList(RegisterViewModelList, "Id", "UserName", RegisterModel.UserId);
            List<RoleModelVM> roleModelVmList = this.Bridge.Role.GetRoles();
            ViewBag.RoleId = new System.Web.Mvc.SelectList(roleModelVmList, "Id", "RoleName", RegisterModel.RoleId);
            return View();
        }

        public ActionResult ResetPassword()
        {
            List<RegisterViewModel> RegisterViewModelList = this.Bridge.Accounts.GetListOfUsers();
            ViewBag.UserID = new System.Web.Mvc.SelectList(RegisterViewModelList, "Id", "UserName");
            return View();
        }

        [HttpPost]
        public ActionResult ResetPassword(RegisterViewModel RegisterViewModel)
        {
            if (!string.IsNullOrEmpty(RegisterViewModel.Password))
            {
                this.Bridge.Role.UpdateRegisterUsers(RegisterViewModel);
                ViewBag.Status = "Success";
                ViewBag.Message = "User  is  Updated Successfuly";
            }
            else
            {
                ViewBag.Status = "Fail";
                ViewBag.Message = "Please check the fields";
            }
            List<RegisterViewModel> RegisterViewModelList = this.Bridge.Accounts.GetListOfUsers();
            ViewBag.UserID = new System.Web.Mvc.SelectList(RegisterViewModelList, "Id", "UserName", RegisterViewModel.Id);
            return View();
        }

        public JsonResult GetUserByContact(int ContactId)
        {
            var Contact = this.Bridge.ccContactUtility.GetContactDetailByContactId(ContactId);
            return Json(Contact, JsonRequestBehavior.AllowGet);
        }

    }
}
       
